{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e788288d-c7d7-4e16-8047-e227c91f10ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import lightgbm as lgb\n",
    "import pickle\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import accuracy_score, classification_report\n",
    "\n",
    "# 从 feature_engineering 模块导入预处理函数\n",
    "from feature_engineering import preprocess_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d053b7fb-32dd-4d8b-a1bd-e532c54e9148",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 模型预测\n",
    "def load_models_and_predict(X_test, models_dir, epochs=10):\n",
    "    results = []\n",
    "\n",
    "    for i in range(epochs):\n",
    "        model_path = f'{models_dir}model_lgb_{i}.pkl'\n",
    "        with open(model_path, 'rb') as f:\n",
    "            model_lgb = pickle.load(f)\n",
    "        \n",
    "        # 使用加载的模型进行预测\n",
    "        print(f'Predicting set {i}')\n",
    "        test_probabilities = model_lgb.predict_proba(X_test, num_iteration=model_lgb.best_iteration_)[:, 1]\n",
    "        results.append(test_probabilities)\n",
    "    \n",
    "    # 集成多次训练的结果\n",
    "    result_probabilities = np.mean(results, axis=0)\n",
    "    result = np.where(result_probabilities > 0.5, 1, 0)\n",
    "    \n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa91707b-c408-4c5f-a091-a3991947a58b",
   "metadata": {},
   "outputs": [],
   "source": [
    "if __name__ == \"__main__\":\n",
    "    # 定义数据文件路径\n",
    "    test_path = '../init_data/raw/测试集B/test_b_x.csv'\n",
    "    # 预处理数据\n",
    "    test_data = preprocess_data(test_path)\n",
    "    user_id = test_data['user_id']\n",
    "    test_data = test_data.drop('user_id', axis=1)\n",
    "    # 训练集和测试集\n",
    "    pred = load_models_and_predict(test_data,'model/')\n",
    "\n",
    "    # 保存预测结果\n",
    "    result = pd.DataFrame()\n",
    "    result['user_id'] = user_id; result['label'] = pred\n",
    "    result.to_csv('../result/result.csv', index=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
